using System;
using System.Windows.Forms;

namespace ShadeTree.Binding.Elements
{
    public class RadioElement<ENUM> : BoundScreenElement<RadioButton, ENUM>
    {
        private readonly RadioButtonGroup<ENUM> _group;
        private ENUM _boundValue;

        public RadioElement(Accessor accessor, RadioButton control, RadioButtonGroup<ENUM> group)
            : base(accessor, control)
        {
            _group = group;
            _group.Add(this);
            Alias = control.Text;
            control.CheckedChanged += control_CheckedChanged;
        }

        public ENUM BoundValue
        {
            get { return _boundValue; }
            set { _boundValue = value; }
        }

        internal bool Latched { get; set; }


        public override void EnableControl(IScreenState state)
        {
            Latched = true;
            base.EnableControl(state);
            Latched = false;
        }

        protected override void tearDown()
        {
            BoundControl.CheckedChanged += control_CheckedChanged;
        }

        private void control_CheckedChanged(object sender, EventArgs e)
        {
            elementValueChanged();
        }


        public override bool ApplyChanges()
        {
            if (!BoundControl.Checked)
            {
                return true;
            }

            base.ApplyChanges();
            return true;
        }

        protected override ENUM getValueFromControl()
        {
            return _boundValue;
        }

        protected override void resetControl(ENUM originalValue)
        {
            _group.LatchPeers(this);
            BoundControl.Checked = originalValue.Equals(_boundValue);
            _group.UnLatchPeers(this);
        }

        public void RegisterOnClickHandler(Action handler)
        {
            BoundControl.Click += delegate
                                      {
                                          runIfNotLatched(()=>handler());
                                      };
        }
    }
}